package encaps.action;

import encaps.resources.Response;
import encaps.utils.StringUtil;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import encaps.utils.search.SearchContext;
import encaps.utils.search.Searcher;
import org.jdom.Element;

public class BasicSearchAction extends AbstractSearchAction {

    public static final String BASIC_SEARCH = "basicSearch";
    public static final String SEARCH_PARAMETER = "parameter";
    public static final String ENTITY_TYPE = "searchType";

    public BasicSearchAction(ActionContext context) {
        actionContext = context;
    }

    public Element execute() throws ActionExecutionException {
        try {
            String entityType = actionContext.getTextParameter(ENTITY_TYPE);
            Searcher searcher = searchers.get(entityType);
            SearchContext searchContext = getSearchContext();
            Element resultXML = XMLHelper.createElement(Response.RESPONSE);
            Element foundResults = searcher.getResult(searchContext);
            XMLHelper.addChild(resultXML, foundResults);
            return resultXML;
        } catch (Exception e) {
            throw new ActionExecutionException(e);
        }
    }

    @Override
    protected SearchContext createEmptySearchContext() {
        return new SearchContext(true);
    }

    @Override
    protected void fillContextWithSearchingParameters(SearchContext context) throws SystemException {
        context.setEntityType(actionContext.getTextParameter(ENTITY_TYPE));

        String searchParameter = actionContext.getTextParameter(SEARCH_PARAMETER);
        searchParameter = StringUtil.getValidValue(searchParameter);
        context.addSearchParameter(SEARCH_PARAMETER, searchParameter);

        context.setActionName(BASIC_SEARCH);
    }
}
